// pages/search/search.js
import request from '../../utils/request'
let isSend = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //搜索提示
    placeHolderContent: '',
    //热搜榜数据
    hotList: [],
    //用户输入的表单项数据
    searchContent: '',
    //搜索数据
    searchList: [],
    historyList: [], //搜索历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getplaceHolderContent()
    this.getHotList()
    this.getSearchHistory()
  },
  //搜索关键字接口
  async getplaceHolderContent() {
    const placeHolderData = await request('/search/default')
    this.setData({
      placeHolderContent: placeHolderData.data.showKeyword
    })
  },
  // 热搜榜接口
  async getHotList() {
    const hotListData = await request('/search/hot/detail')
    this.setData({
      hotList: hotListData.data
    })
  },
  //获取搜索列表
  async getSearchList() {
    if (!this.data.searchContent) {
      return;
    }

    let { searchContent, historyList } = this.data;

    const searchListData = await request('/search', { keywords: this.data.searchContent, limit: 15 })
    this.setData({
      searchList: searchListData.result.songs
    })

    //将搜索的历史记录添加到历史记录中去
    let isRight
    historyList.forEach(element => {
      if (element.val == searchContent) {
        isRight = true
      }
    });
    if (isRight) {
      console.log("执行");
      return;
    }
    let index = this.data.historyList.length
    let historyObj = {
      id: index,
      val: searchContent
    }
    historyList.unshift(historyObj);
    this.setData({
      historyList
    })
    wx.setStorageSync('searchHistory',historyList)
  },
  //表单项内容发生改变的回调
  handleInputChange(event) {
    this.setData({
      searchContent: event.detail.value.trim()
    })

    //函数节流
      if (isSend) {
        return
      }
    isSend = true
    this.getSearchList()
    setTimeout(() => {
      isSend = false
    },3000)
  },

  //获取本地搜索记录的方法
  getSearchHistory() {
    let historyList = wx.getStorageSync('searchHistory')
    if (historyList) {
      this.setData({
        historyList
      })
    }
  },

  // 取消搜索
  cancelSearch() {
    this.setData({
      searchContent:''
    })
  },
  //删除搜索历史记录
  deleteSearchHistory() {
    wx.showModal({
      content: '确定要删除所有的历史记录？',
      success:(res)=>{
        if (res.confirm) {
          this.setData({
            historyList:[]
          })
          wx.removeStorageSync('searchHistory')
        }
      },
    })
  
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})